package com.qin.dao;

import java.sql.SQLException;
import java.util.List;

import com.qin.entity.Order;

import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import cn.hutool.db.handler.BeanHandler;

/**
 * 操作Order类
 * @author BestRiven
 *
 */
public class OrderDao {

	/**
	 * 插入一个订单
	 * @param order 要插入的订单
	 * @return 自增id
	 */
	public Long insertOrder(Order order) {
		Entity record = Entity.parseWithUnderlineCase(order);
		Long insertForGeneratedKey = 0L;
		try {
			insertForGeneratedKey = Db.use().insertForGeneratedKey(record);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return insertForGeneratedKey;
	}
	
	/**
	 * 逻辑删除订单
	 * @param id 要删除的订单id
	 * @return 影响行数（0代表失败）
	 */
	public int logicDeleteOrder(Long id) {
		String sql = "UPDATE `order` SET `status` = 0 WHERE `id` = ?";
		int execute = 0;
		try {
			execute = Db.use().execute(sql, id);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return execute;
	}
	
	/**
	 * 修改订单
	 * @param id 要修改订单的id
	 * @param order 修改订单的信息
	 * @return 影响行数
	 */
	@Deprecated
	public int updateOrder(Long id, Order order) {
		return 0;
	}
	
	/**
	 * 通过订单id查询订单
	 * @param id
	 * @return
	 */
	public Order queryOrderById(Long id) {
		Entity where = Entity.create("order").set("id", id).set("status", 1);
		Order find = null;
		try {
			find = Db.use().find(where, new BeanHandler<Order>(Order.class));
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return find;
	}
	
	/**
	 * 根据用户id查询所有的订单
	 * @param id 用户id
	 * @return 所有的订单
	 */
	public List<Order> queryOrdersByUserId(Long id){
		Entity where = Entity.create("order").set("user_id", id).set("status", 1);
		List<Order> find = null;
		try {
			find = Db.use().find(where, Order.class);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return find;
	}
}
